<template>
  <div class="view-pic-thumb">
    <div style="position: relative;" v-for="(thumb, pIndex) in originalData.thumbs">
      <van-image fit="contain" lazy-load :width="size.width" :height="size.height" :src="thumb.url" @click="viewPicFn"></van-image>
      <van-icon v-if="delFlag" style="position:absolute;top:0;right:0" name="clear" @click="delPicFn(thumb, pIndex)"></van-icon>
    </div>
  </div>
</template>

<script>
import {SPLIT_COMMA, SPLIT_BLANK} from "@/api/enum";
import {loadPicThumb} from "@/components/file-upload/upload_file";

export default {
  name: "viewPicThumb",
  props: {
    originalData: {
      type: Object,
      default() {
        return {
          pics: SPLIT_BLANK,    // 图片名称，逗号分隔
          thumbs: [],  // 缩略图url
        }
      }
    },
    size: {
      type: Object,
      default() {
        return {
          width: '20vw',
          height: '20vvw'
        }
      }
    },
    firstFlag: {
      type: Boolean,
      default: false
    },
    delFlag: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      /* 图片预览 */
      viewPic: {
        show: false,
        urls: []
      },
    }
  },
  mounted() {
    const that = this;
    if(!that.originalData.pics) {
      that.originalData.pics = SPLIT_BLANK;
    }
    if(!that.originalData.thumbs) {
      that.originalData.thumbs = [];
    }
    if(that.originalData.thumbs.length === 0) {
      let pics = that.originalData.pics.split(SPLIT_COMMA).filter(pic => pic !== SPLIT_BLANK);
      that.viewPicThumbFn(pics, 0);
    }
  },
  methods: {
    /* 缩略图 */
    viewPicThumbFn(pics, index) {
      const that = this;
      let pic = pics[index];
      if(pic) {
        loadPicThumb(that, pic, resPic => {
          that.originalData.thumbs.push({
            name: pic,
            url: resPic
          });
          that.$forceUpdate();
          that.$nextTick(() => {
            if(that.firstFlag) {    //只要一个
              return;
            }
            that.viewPicThumbFn(pics, ++index);
          });
        });
      }
    },

    /* 显示预览 */
    viewPicFn() {
      const that = this;
      that.$emit("view", that.originalData);
    },

    /* 删除图片 */
    delPicFn(thumb, pIndex) {
      const that = this;
      /*if(that.originalData.thumbs.length === 1) {
        that.$toast.fail("至少保留一张图片")
        return;
      }*/
      that.originalData.thumbs.splice(pIndex, 1);   //移除缩略图
      if(that.originalData.picObjs && that.originalData.picObjs.length > 0) {   //移除预览
        let i = that.originalData.picObjs.findIndex(picObj => picObj.name === thumb.name);
        if(i >= 0) {
          that.originalData.picObjs.splice(i, 1);
        }
      }
      let pics = that.originalData.pics.split(SPLIT_COMMA);
      pics.splice(pics.indexOf(thumb.name), 1);
      that.originalData.pics = pics.join(SPLIT_COMMA);
    },
  }
}
</script>

<style lang="scss" scoped>
.view-pic-thumb {
  display: flex;
  flex-wrap: wrap;
}
</style>